//
//  ViewController.m
//  LittleSummary
//
//  Created by 郝旭珊 on 2018/1/4.
//  Copyright © 2018年 郝旭珊. All rights reserved.
//

#import "ViewController.h"
#import "BlockController.h"
#import "SecondController.h"
#import "TableViewController.h"

#import "DrawView.h"
#import "FMDBManger.h"

@interface ViewController ()

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor orangeColor];

}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    BlockController *vc = [BlockController new];
//    __weak typeof(self) weakSelf = self;
//    vc.passSearchText = ^(NSString *text) {
//        [weakSelf setupSearchBarUI:text];
//    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setupSearchBarUI:(NSString *)text{

}


- (void)sqlite{
    NSDictionary *dict = @{@"name":@"sense",
                           @"price":@(9999),
                           @"description":@"heart is complex",
                           @"number":@(1)
                           };

    NSDictionary *dict1 = @{@"name":@"meaning",
                            @"price":@(9),
                            @"description":@"heart is positive",
                            @"number":@(3)
                            };

    NSDictionary *dict2 = @{@"id":@(13),
                            @"name":@"peace",
                            @"price":@(111111),
                            @"description":@"heart is like mirror",
                            @"number":@(365)
                            };


    //    [self insertSql];
    //    [self insertSqlWithDict:dict];

    [self deleteSql];
    //    [self deleteSqlWithName:@"fear"];
    //    [self deleteSqlWithId:[NSNumber numberWithInt:6]];
    //    [self deleteSqlWithIdInt:5];

    //    [self updateSql];
    //    [self updateSqlWithDict:dict1];

    //    [self selectSql];
    //    [self selectSql2];

    //    [self normalInserWithDict:dict];
    [self transactionInsertWithDict:dict1];
}


- (void)transactionInsertWithDict:(NSDictionary *)dict{
    NSString *sql = @"INSERT INTO T_Goods (name,price,description,number) VALUES (:name,:price,:description,:number);";
    double startTime = CACurrentMediaTime();

    [[FMDBManager sharedManager].queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        for (int i=0;i<10000;i++){
            if (![db executeUpdate:sql withParameterDictionary:dict]){
                *rollback = YES;
                NSLog(@"插入出现错误");
                break; //退出 for 循环
            }

            //模拟断电
//            if (i == 100){
//                *rollback = YES;
//                break;
//            }
        }

        double useTime = CACurrentMediaTime() - startTime;
        NSLog(@"transaction所用时长:%f",useTime);
        //transaction所用时长:0.299979
    }];

}



- (void)normalInserWithDict:(NSDictionary *)dict{
    NSString *sql = @"INSERT INTO T_Goods (name,price,description,number) VALUES (:name,:price,:description,:number);";
    double startTime = CACurrentMediaTime();

    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        for (int i=0;i<10000;i++){
            if (![db executeUpdate:sql withParameterDictionary:dict]){
                NSLog(@"插入出现错误");
                break; //退出 for 循环
            }
        }

        double useTime = CACurrentMediaTime() - startTime;
        NSLog(@"normal所用时长:%f",useTime);
        //normal所用时长:16.192206
    }];

}


- (void)selectSql2{
    NSString *sql = @"SELECT id, name, price, description, number FROM T_Goods;";
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray *result = [[FMDBManager sharedManager] executeSelectSql:sql];
        NSLog(@"%@",result);
    });
}


- (void)selectSql{
    NSString *sql = @"SELECT id, name, price, description, number FROM T_Goods;";
    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:sql];
        if (!rs){
            NSLog(@"没有查询到结果");
            return;
        }

        NSMutableArray *result = [NSMutableArray array];

        // while ([rs next]) FMDB 中的方法
        while ([rs next]) {
            //列数(属性数)
            NSInteger colCount = [rs columnCount];
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];

            //遍历某一行的全部列, 得到一个完整的对象字典
            for (int i=0;i<colCount;i++){
                //第 i 列的属性名
                NSString *name = [rs columnNameForIndex:i];
                //第 i 列的属性值
                id obj = [rs objectForColumnIndex:i];
                [dict setValue:obj forKey:name];
            }
            [result addObject:dict];
        }

        NSLog(@"%@",result);
    }];

}


- (void)updateSqlWithDict:(NSDictionary *)dict{
    //常犯错误 和insert语句混淆
//    NSString *sql = @"UPDATE T_Goods set (name,price,description,number) VALUE (:name,:price,:description,:number) WHERE id = :id;";
    NSString *sql = @"UPDATE T_Goods set name = :name, price = :price, description = :description ,number = :number WHERE id = :id;";
    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql withParameterDictionary:dict]){
            NSLog(@"修改了%d行",db.changes);
        }else{
            NSLog(@"修改失败");
        }
    }];
}


- (void)updateSql{
    NSString *sql = @"UPDATE T_Goods set name = 'happiness' WHERE id = 5;";
    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql]){
            NSLog(@"修改成功");
        }else{
            NSLog(@"修改失败");
        }
    }];
}

- (void)deleteSqlWithName:(NSString *)name{
    NSString *sql = @"DELETE FROM T_Goods WHERE name = :name;";
    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql,name]){
            NSLog(@"删除了%d行",db.changes);
        }else{
            NSLog(@"删除失败");
        }
    }];
}



- (void)deleteSqlWithId:(NSNumber *)Id{
    NSString *sql = @"DELETE FROM T_Goods WHERE id = :id;";
    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql,Id]){
            NSLog(@"删除了%d行",db.changes);
        }else{
            NSLog(@"删除失败");
        }
    }];
}

//错误, 增改查中只要是基本类型的value 都要转换为NSNumber 否则会崩溃
- (void)deleteSqlWithIdInt:(int)Id{
    NSString *sql = @"DELETE FROM T_Goods WHERE id = :id;";
    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql,Id]){
            NSLog(@"删除了%d行",db.changes);
        }else{
            NSLog(@"删除失败");
        }
    }];
}



- (void)deleteSql{
    NSString *sql0 = @"DELETE FROM T_Goods";
    NSString *sql1 = @"DELETE FROM T_Goods WHERE id = 2;";
    NSString *sql2 = @"DELETE FROM T_Goods WHERE name = 'happy';";
    NSString *sql3 = @"DELETE FROM T_Goods WHERE name LIKE '%ear%';";
    NSString *sql = [sql2 stringByAppendingString:sql3];

    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql0]){
            NSLog(@"删除成功");
        }else{
            NSLog(@"删除失败");
        }
    }];
}


- (void)insertSqlWithDict:(NSDictionary *)dict{
    NSString *sql = @"INSERT INTO T_Goods (name,price,description,number) VALUES (:name,:price,:description,:number);";
    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql withParameterDictionary:dict]){
            NSLog(@"插入成功");
        }else{
            NSLog(@"插入失败");
        }
    }];
}


- (void)insertSql{
    NSString *sql = @"INSERT INTO T_Goods (name,price,description,number) VALUES ('happy',22,'can not buy',1);";
    [[FMDBManager sharedManager].queue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql]){
            NSLog(@"插入完成");
        }else{
            NSLog(@"插入失败");
        }
    }];

}



- (void)addDrawView{
    self.view.backgroundColor = [UIColor orangeColor];
    DrawView *drawView = [[DrawView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    drawView.backgroundColor = WHITECOLOR;
    [self.view addSubview:drawView];
}

- (NSObject *)getObj{
    return [[NSObject alloc] init];
}


/**
 * for 循环
 */
- (void)forCycle{
    NSArray *titles = @[@"break",@"return",@"continue",@"stop"];
    for (int i=0;i<4;i++){
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100+30*i, 60, 30)];
        btn.backgroundColor = [UIColor redColor];
        [btn setTitle:@"for" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    }
}




@end
